<?php

namespace Lib;

final class Passwd {
    use \Lib\Traits\StaticClass;
    
    /**
     * 加密
     *
     * @param string $needle
     * @param string $secure
     * @return string
     */
    public static function encrypt($needle, $secure = null) {
        $mustStr = !$secure ? \Yaf\Registry::get('config')->get('resources.salt.passwd') : $secure;

        $md5str  = md5($needle . ':' . $mustStr);
        $randArr = str_split($md5str, 2);
        $randStr = strrev($randArr[mt_rand(0, count($randArr) - 1)]);

        return sha1($md5str . ':' . $randStr) . ':' . $randStr;
    }

    /**
     * 验证
     *
     * @param string $input
     * @param string $needle
     * @param string $secure
     *
     * return boolean
     */
    public static function valid($input, $needle, $secure = null) {
        $mustStr   = $secure === null ? \Yaf\Registry::get('config')->get('resources.salt.passwd') : $secure;
        $needleArr = explode(':', $needle);

        if (count($needleArr) == 2) {
            $sha1Str = sha1(md5($input . ':' . $mustStr) . ':' . $needleArr[1]);

            if (strcmp($sha1Str, $needleArr[0]) === 0) {
                return true;
            }
        }

        return false;
    }
}
